import { defineStore } from 'pinia'
import axios from 'axios'

export const useQuestionStore = defineStore('question', {
  state: () => ({
    questions: [],
    error: null
  }),
  
  actions: {
    // 获取所有题目
    async getAllQuestions() {
      try {
        console.log('正在获取题目列表...')
        const response = await axios.get('/api/questions')
        console.log('获取到的题目:', response.data)
        return response.data
      } catch (error) {
        console.error('获取题目列表失败:', error)
        console.error('错误详情:', error.response || error)
        throw new Error(
          error.response?.data?.error || 
          error.message || 
          '获取题目列表失败'
        )
      }
    },

    // 删除题目
    async deleteQuestion(id) {
      try {
        await axios.delete(`/api/questions/${id}`)
      } catch (error) {
        console.error('删除题目失败:', error)
        throw new Error(error.response?.data?.error || '删除题目失败')
      }
    },

    async addQuestion(question) {
      try {
        console.log('发送请求到服务器:', question)
        const response = await axios.post('/api/questions', {
          content: question.content,
          answer: question.answer,
          imageUrl: question.imageUrl || '',
          hint: question.hint || ''
        })
        console.log('服务器响应:', response.data)
        return response.data
      } catch (error) {
        console.error('API错误:', error)
        console.error('请求 URL:', error.config?.url)
        console.error('错误详情:', error.response || error)
        throw new Error(
          error.response?.data?.error || 
          error.message || 
          '网络请求失败'
        )
      }
    },

    async getRandomQuestion() {
      try {
        const response = await axios.get('/api/questions/random')
        return response.data
      } catch (error) {
        console.error('获取题目失败:', error)
        throw new Error(error.response?.data?.error || '获取题目失败')
      }
    },

    async getRandomQuestions(count = 10) {
      try {
        const promises = Array(count).fill().map(() => this.getRandomQuestion())
        return await Promise.all(promises)
      } catch (error) {
        console.error('获取随机题目失败:', error)
        throw new Error(error.response?.data?.error || '获取题目失败')
      }
    }
  }
}) 